package cn.edu.csust.coursecard.utils.storage;

import cn.edu.csust.coursecard.common.CodeEnum;
import cn.edu.csust.coursecard.exception.BaseException;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Data
@Component
@ConfigurationProperties(prefix = "qiniu")
public class QiniuUtils {

    private String bucket;

    private String accessKey;

    private String accessSecretKey;

    private String url;

    public void upload(MultipartFile file, String fileName) {
        byte[] uploadBytes = new byte[0];
        try {
            uploadBytes = file.getBytes();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        upload(uploadBytes, fileName);
    }

    public void upload(byte[] uploadBytes, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
            uploadManager.put(uploadBytes, fileName, upToken);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new BaseException(CodeEnum.PICTURE_UPLOAD_ERROR.getCode(), "文件上传失败");
        }
    }

    //删除文件
    public void delete(String fileName) {
        Configuration configuration = new Configuration(Region.region2());
        Auth auth = Auth.create(accessKey, accessSecretKey);
        BucketManager bucketManager = new BucketManager(auth, configuration);
        try {
            bucketManager.delete(bucket, fileName);
        } catch (QiniuException ex) {
            throw new BaseException(CodeEnum.PICTURE_DELETE_ERROR.getCode(), fileName + "文件删除失败");
        }
    }


}
